package com.mygenostics.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import com.mygenostics.persistence.UserBean;

public class UserDAO {
	private static final String GET_USER_BY_NAME = "from usr as u left outer join fetch u.userFiles as userFiles where u.userName = ?";	
	
	public UserBean getUserByName(String userName) {
		
		EntityManager em = DAOFactory.getEMF().createEntityManager();
		
		try {
//			UserBean user = em.createQuery(GET_USER_BY_NAME, UserBean.class)
//								.setParameter(1, userName).getSingleResult();
			
			TypedQuery<UserBean> query = em.createQuery(GET_USER_BY_NAME, UserBean.class).setParameter(1, userName);
			
			UserBean user = query.getSingleResult();
			
			return user;
		}
		catch (NoResultException nre) {
			return null;
		}
		finally {
			em.close();
		}
	}
	
	public UserBean createUser(UserBean user) {
		EntityManager em = DAOFactory.getEMF().createEntityManager();
		
		try {
			em.getTransaction().begin();
			em.persist(user);
			em.getTransaction().commit();
			
			return user;
		}
		finally {
			em.close();
		}
	}
	
	/*
	 * This method called for clean test data only
	 */
	public void deleteAllUsers() {
		EntityManager em = DAOFactory.getEMF().createEntityManager();
		
		try {
			em.getTransaction().begin();
			em.createQuery("delete from usr").executeUpdate();
			em.getTransaction().commit();
		}
		finally {
			em.close();
		}
	}
	
	public void deleteUserByName(String userName) {
		EntityManager em = DAOFactory.getEMF().createEntityManager();
		
		try {
			em.getTransaction().begin();
			em.createQuery("delete from usr u where u.userName = ?")
				.setParameter(1, userName).executeUpdate();
			em.getTransaction().commit();
		}
		finally {
			em.close();
		}
	}
}
